import os
from typing_extensions import Annotated

from fastapi import Depends, Form, Path
from core.database import db_session
from core.exception import AlertException
from core.models import Board
from lib.common import dynamic_create_write_table


def get_variery_board(
        board_path: Annotated[str, Path(alias="bo_table")] = None,
        board_form: Annotated[str, Form(alias="bo_table")] = None,
):
    """
    按请求参数的类型 bo_table收货, 一个 bo_table 仅返回值
    - 按函数参数的顺序具有优先级
    """
    return board_path or board_form


def get_board(db: db_session, bo_table: Annotated[str, Depends(get_variery_board)]):
    """检查公告板的存在 & 返回"""
    board = db.get(Board, bo_table)
    if not board:
        raise AlertException(f"{bo_table} : 这是一个不存在的公告板.", 404)

    return board


def get_variery_wr_id(
        wr_id_path: Annotated[str, Path(alias="wr_id")] = None,
        wr_id_form: Annotated[str, Form(alias="wr_id")] = None,
):
    """
    按请求参数的类型 wr_id收货, 一个 wr_id 仅返回值
    - 按函数参数的顺序具有优先级
    """
    return wr_id_path or wr_id_form


async def get_write(db: db_session, 
              bo_table: Annotated[str, Path(...)],
              wr_id: Annotated[int, Depends(get_variery_wr_id)]):
    """检查是否有哨所 & 返回"""
    if not wr_id.isdigit():
        raise AlertException(f"{wr_id} : 这是一个不正确的帖子编号.", 404)

    write_model = dynamic_create_write_table(bo_table)
    write = db.get(write_model, wr_id)
    if not write:
        raise AlertException(f"{wr_id} : 这是一个不存在的帖子.", 404)

    return write
